<?php


namespace app\common\cachemodel\lucky;


use app\common\lib\exception\ApiException;
use app\common\lib\SensorsData;
use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class AppUserLuckyInfo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_lucky_info';

    protected $cacheModel = 'lucky_planet.user_details';

    /**
     * 幸运星首页 获取用户幸运星信息 及幸运星销毁信息
     * @param int $uid
     * @return array|mixed
     * @throws ApiException
     */
    public function IndexGetUserLuckyInfo(int $uid)
    {
        $luckyInfo = $this->getInfoById($uid, ['lucky_num']);

        if ($luckyInfo)
        {   // 有幸运星 信息 通过了 销毁旧幸运星 或新用户通过了
            $luckyInfo['first_info'] = null;
            $luckyInfo['lucky_num'] = max($luckyInfo['lucky_num'], 0);
        } else
        {
            $luckyInfo = [
                'lucky_num' => 0,
                'first_info' => null
            ];
            //  判断有没有 旧的幸运星需要销毁 并销毁
            $compensate = (new AppUserOldLuckyRecycle())->getUserRecycleInfo($uid);
            if ($compensate)
            {   // 有  旧版本幸运星 并销毁
                $luckyInfo['first_info'] = $compensate;
            } else
            {
                // 如果没有 直接 初始化该用户幸运星信息
                $this->save([
                    'uid' => $uid,
                    'lucky_num' => 0,
                    'total_lucky_num' => 0,
                    'use_lucky_num' => 0,
                    'expired_lucky_num' => 0,
                    'create_time' => time(),
                    'update_time' => 0,
                ]);
            }
        }

        return $luckyInfo;
    }

    /**
     * 初始化 用户幸运星 信息
     * @param int $uid
     * @return bool
     */
    public function SaveData(int $uid)
    {
        try
        {
            $this->save([
                'uid' => $uid,
                'lucky_num' => 0,
                'total_lucky_num' => 0,
                'use_lucky_num' => 0,
                'expired_lucky_num' => 0,
                'create_time' => time(),
                'update_time' => 0,
            ]);
        }
        catch (\Exception $e)
        {
            Log::write('旧幸运星销毁 AppUserLuckyInfo()->SaveData 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
        return true;
    }

    public function UpdateData(int $id, int $uid, array $updateData)
    {
        try
        {
            $this->where(['id' => $id])->update($updateData);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();

            return true;
        }
        catch (\Exception $e)
        {
            Log::write('问答 AppUserLuckyInfo model => UpdateData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 用户 幸运星 发放
     * @param int $uid
     * @param int $taskId
     * @param string $taskType //领取类型  签到、每日任务、升级任务、其他任务
     * @return bool
     */
    public function userLuckyNumSend(int $uid, int $taskId, string $taskType = '')
    {
        $nowTime = time();
        $userLuckyChangeRecordModel = new AppUserLuckyChangeRecord();
        try
        {
            $luckyTaskConfig = config('lucky_task.task_list');
            $taskInfo = $luckyTaskConfig[$taskId];
            // 获取 用户幸运星 信息
            $userLuckyInfo = $this->getInfoById($uid);
            if (!$userLuckyInfo)
            {
                return false;
            }
            $updateData = [
                'lucky_num' => $userLuckyInfo['lucky_num'] + $taskInfo['lucky_num'],
                'total_lucky_num' => $userLuckyInfo['total_lucky_num'] + $taskInfo['lucky_num'],
                'update_time' => $nowTime
            ];
            // 发放用户幸运星
            $this->UpdateData($userLuckyInfo['id'], $uid, $updateData);

            // 写入 幸运星 发放记录
            $data = [
                'status' => 0,
                'uid' => $uid,
                'type' => 1,    // 记录类型 1=>领取 2=>兑换使用 3=>抽奖使用 4=>过期销毁
                'use_num' => 0,
                'change_num' => $taskInfo['lucky_num'],
                'changeed_num' => $updateData['lucky_num'],
                'task_id' => $taskId, // 签到任务ID
                'draw_id' => 0,
                'exchange_id' => 0,
                'expire_time' => $nowTime + 86400 * $userLuckyChangeRecordModel->luckyExpireDay,
                'extend' => '',
                'create_time' => $nowTime,
                'update_time' => 0,
            ];
            $userLuckyChangeRecordModel->SaveData($data);

            // 神策打点 12 领取幸运星 LuckyPlanetGet
            SensorsData::track($uid, true, 'LuckyPlanetGet', [
                'star_num' => $taskInfo['lucky_num'],   // 领取幸运星数量
                'task_type' => $taskType,      //领取类型  签到、每日任务、升级任务、其他任务
                'task_name' => $taskInfo['name'],    // 领取项目
                'star_left' => $updateData['lucky_num'], // 领取后的余额
            ]);
        }
        catch (\Exception $e)
        {
            Log::write('任务完成领取幸运星 AppUserLuckyInfo()->SaveData 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
        return true;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|void
     * @throws ApiException
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            return $this->whereIn('uid', $ids)->column('id,lucky_num,total_lucky_num,use_lucky_num,expired_lucky_num,create_time,update_time', 'uid');
        }
        catch (\Exception $e)
        {
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $id => $itemData)
        {
            $resData[$id] = arrayKeyData2int($itemData, ['id', 'lucky_num', 'total_lucky_num', 'use_lucky_num', 'expired_lucky_num', 'create_time', 'update_time', 'uid']);
        }

        return $resData;
    }
}
